<?php

namespace Common\TagLib;

/**
 * Class TagLibXcallinput
 * @since 1.0 2014-10-29 by sutroon
 */
class Sohtml extends TagBase {

    protected $tags = array(
        'select' => array('attr' => 'attrs', 'close' => 0),
        'treeselect' => array('attr' => 'attrs', 'close' => 0),
        'tree' => array('attr' => 'attrs', 'close' => 0),
        'sqlexpselect' => array('attr' => 'attrs', 'close' => 0),
        'radio' => array('attr' => 'attrs', 'close' => 0),
        'checkbox' => array('attr' => 'attrs', 'close' => 0),
        'buttons' => array('attr' => 'attrs', 'close' => 0),
        'file' => array('attr' => 'attrs', 'close' => 0),
        'region' => array('attr' => 'attrs', 'close' => 0),
        'sortlink' => array('attr' => 'attrs', 'close' => 0),
    );

    /**
     * 生成select控件
     * @param $attr
     * @param $content
     * @return string
     * @since 1.0 2014-10-30 sutroon Added.
     * @since 1.1 2015-3-26 SoChishun 新增first-item选项
     * @since 1.2 <2015-10-22> SoChishun 改进items属性，支持json参数
     * @since 1.3 <2015-12-2> SoChishun 新增valuefield,textfield属性
     * @example 
     * <sohtml:select max="10" />
     * <sohtml:select items="v1=name1;v2=name2" />
     * <sohtml:select name="siteID" class="easyui-combobox" title="请选择租户" required="required" min="1" max="30" skips="{$filter}" data-lock-value="textbox-readonly"/>
     * <sohtml:select name="{$data.set}" valuefield="id" textfield="title" />
     */
    public function _select($attr, $content) {
        //$attr = $this->parseXmlAttr($attr, 'select');
        $value = $attr['value'];
        $vfield = empty($attr['valuefield']) ? 'v' : $attr['valuefield'];
        $tfield = empty($attr['textfield']) ? 't' : $attr['textfield'];
        $first_item = empty($attr['first-item']) ? '请选择' : $attr['first-item'];
        if ('none' == $first_item) {
            $first_item = '';
        }
        $lockValue = $attr['data-lock-value'];
        $disabled = '';
        if ($value) {
            $value = $this->base_get_tpl_data($value);
            if ($value && $lockValue) {
                switch ($lockValue) {
                    case 'textbox-readonly':
                        return '<input type="text" name="' . $attr['name'] . '" value="' . $value . '" readonly="readonly" />';
                    default:
                        $disabled = ' disabled="disabled"';
                        break;
                }
            }
        }
        $aitems = $this->base_parse_items_array($attr);
        $str = $first_item ? '<option value="">' . $first_item . '</option>' : '';
        if (is_array(current($aitems))) {
            foreach ($aitems as $item) {
                $str .= '<option value="' . $item[$vfield] . '"' . (strlen($item[$vfield]) > 0 && $value == $item[$vfield] ? ' selected="selected"' : '') . '>' . $item[$tfield] . '</option>';
            }
        } else {
            foreach ($aitems as $val => $txt) {
                $str .= '<option value="' . $val . '"' . (strlen($value) > 0 && $value == $val ? ' selected="selected"' : '') . '>' . $txt . '</option>';
            }
        }
        $str = '<select name="' . $attr['name'] . '"' . $this->base_attr_to_string($attr, array('items', 'items_pair', 'items_splitor1', 'items_splitor2', 'min', 'max', 'step', 'value', 'data-lock-value', 'skip')) . $disabled . '>' . $str . '</select>';
        return $str;
    }

    /**
     * 生成树形<select />标签
     * @param type $attr
     * @param type $content
     * @return string
     * @since 1.0 <2015-3-25> SoChishun Added.
     * @example <sohtml:treeselect name="role_id" datasource="role_list" value="{$data.role_id}" />
     */
    public function _treeselect($attr, $content) {
        $str = '';
        $list = $this->tpl->get($attr['datasource']);
        $value = empty($attr['value']) ? '' : $this->base_get_tpl_data($attr['value']);
        $first_item = empty($attr['first-item']) ? '请选择' : $attr['first-item'];
        if ('none' == $first_item) {
            $first_item = '';
        }
        $str = $first_item ? '<option value="">' . $first_item . '</option>' : '';
        return '<select' . $this->base_attr_to_string($attr, array('idfield', 'namefield', 'datasource', 'value')) . '>' . $str . ($list ? $this->treeselect_fnc($list, $value) : '') . '</select>';
    }

    // _treeselect子方法
    function treeselect_fnc($list, $value, $i = 0) {
        $str = '';
        if ($list) {
            $id_field = '';
            $name_field = '';
            foreach ($list as $row) {
                if (!$id_field) {
                    $keys = array_keys($row);
                    $id_field = $keys[0];
                    $name_field = $keys[1];
                }
                $str.='<option value="' . $row[$id_field] . '"' . ($value == $row[$id_field] ? ' selected="selected"' : '') . '>' . str_repeat('--', $i) . $row[$name_field] . '</option>';
                if ($row['sub']) {
                    $str.=$this->treeselect_fnc($row['sub'], $value, $i + 1);
                }
            }
        }
        return $str;
    }

    /**
     * 树形列表
     * @param type $attr
     * @param type $content
     * @return string
     * @since 1.0 2014-10-28 by sutroon
     * @since 1.1 2015-3-26 SoChishun 重构
     */
    public function _tree($attr, $content) {
        // <sohtml:tree datasource="role_list" value="{$data.role_id}" />
        $str = '';
        $list = $this->tpl->get($attr['datasource']);
        $value = empty($attr['value']) ? '' : $this->base_get_tpl_data($attr['value']);
        if (!$list) {
            return '';
        }
        $str = $this->tree_fn($list, $value, true);
        return '<ul class="ul-tree">' . substr($str, 4);
    }

    // tree内部递归方法 2014-10-28 by sutroon
    function tree_fn($list, $checked_values, $checkbox = false) {
        $str = '<ul>';
        $id_name = '';
        $value_name = '';
        foreach ($list as $row) {
            if (!$id_name) {
                $keys = array_keys($row);
                $id_name = $keys[0];
                $value_name = $keys[1];
            }
            $str .= '<li>';
            if ($checkbox) {
                $str .= '<input type="checkbox" name="ids[]" value="' . $row[$id_name] . '"' . ($checked_values && false !== strpos(',' . $checked_values . ',', ',' . $row[$id_name] . ',') ? ' checked="checked"' : '') . ' />';
            }
            $str .= '<strong>' . $row[$value_name] . '</strong>';
            if ($row['sub']) {
                $str .= $this->tree_fn($row['sub'], $checked_values, $checkbox);
            }
            $str .= '</li>';
        }
        $str .= '</ul>';
        return $str;
    }

    /**
     * 生成sql表达式符号(>,>=,=,<,<=,IN,LIKE)下拉列表
     * @param type $attr
     * @param type $content
     * @return string
     * @since 1.0 2014-12-25 by sutroon
     */
    public function _sqlexpselect($attr, $content) {
        //$attr = $this->parseXmlAttr($attr, 'select');
        $value = isset($attr['value']) ? $this->base_get_tpl_data($attr['value']) : '';
        $items = (isset($attr['items']) && $attr['items']) ? explode(',', $attr['items']) : false;
        $skips = (isset($attr['skips']) && $attr['skips']) ? explode(',', $attr['skips']) : false;
        $arr_items = array('EQ' => '等于', 'GT' => '大于', 'EGT' => '大于等于', 'LT' => '小于', 'ELT' => '小于等于', 'IN' => '在里面', 'NEQ' => '不等于', 'LIKE' => '模糊匹配');
        $str = '<option value="">请选择</option>';
        foreach ($arr_items as $val => $txt) {
            if (($items && !in_array($val, $items)) || ($skips && in_array($val, $skips))) {
                continue;
            }
            $str .= '<option value="' . $val . '"' . (strlen($value) > 0 && $value == $val ? ' selected="selected"' : '') . '>' . $txt . '</option>';
        }
        $str = '<select' . $this->base_attr_to_string($attr, array('items', 'value')) . $disabled . '>' . $str . '</select>';
        return $str;
    }

    /**
     * 生成radio控件
     * @param $attr
     * @param $content
     * @return string
     * @since 1.0 2014-11-7 by sutroon
     * @since 1.1 <2015-10-22> SoChishun 改进items属性，支持json参数
     * @example 
     *      <sohtml:radio items="v1=name1;v2=name2" />
     *      <sohtml:radio name="state" items="1=上架;0=下架" value="{$data.state|default=1}" />
     */
    public function _radio($attr, $content) {
        //$attr = $this->parseXmlAttr($attr, 'radio'); tp3.2.3不用此语句
        return $this->get_checkinput('radio', $attr);
    }

    /**
     * 生成checkbox控件
     * @param $attr
     * @param $content
     * @return string
     * @since 1.0 2014-11-7 by sutroon
     * @since 1.1 <2015-10-22> SoChishun 改进items属性，支持json参数
     * @example <sohtml:checkbox items="v1=name1;v2=name2" />
     */
    public function _checkbox($attr, $content) {
        //$attr = $this->parseXmlAttr($attr, 'checkbox');
        return $this->get_checkinput('checkbox', $attr);
    }

    /**
     * 生成多个按钮
     * @param type $attr
     * @param type $content
     * @return string
     * @since 1.0 2015-3-3 by sutroon
     * @example 
     * <sohtml:buttons type="button" items="1{:comma}14,btn1,,2;筆錄,,,3;案情;金融,btn2,idbtn2,5;有錢;沒錢;凍結;留單;送3;出門;過單" onclick="return update_help()" />
     * item内容为：value,name,id,data-value; 如果要在内容中加逗号,需使用符号{:comma}
     */
    public function _buttons($attr, $content) {
        //$attr = $this->parseXmlAttr($attr, 'buttons');
        $items = $attr['items'];
        $type = empty($attr['type']) ? 'button' : $attr['type'];
        $str = '';
        if (!$items) {
            return '';
        }
        $arr_items = explode(';', $items);
        foreach ($arr_items as $item) {
            $arr_item = explode(',', $item);
            $name = '';
            $id = '';
            $dataval = '';
            switch (count($arr_item)) {
                case 1:
                    $val = $item;
                    break;
                case 2:
                    $val = $arr_item[0];
                    $name = $arr_item[1] ? (' name="' . $arr_item[1] . '"') : '';
                    break;
                case 3:
                    $val = $arr_item[0];
                    $name = $arr_item[1] ? (' name="' . $arr_item[1] . '"') : '';
                    $id = $arr_item[2] ? (' id="' . $arr_item[2] . '"') : '';
                    break;
                case 4:
                    $val = $arr_item[0];
                    $name = $arr_item[1] ? (' name="' . $arr_item[1] . '"') : '';
                    $id = $arr_item[2] ? (' id="' . $arr_item[2] . '"') : '';
                    $dataval = $arr_item[1] ? (' data-value="' . str_replace('{:comma}', ',', $arr_item[3]) . '"') : '';
                    break;
            }
            $str .= '<input type="' . $type . '"' . $id . $name . ' value="' . str_replace('{:comma}', ',', $val) . '"' . $dataval . $this->base_attr_to_string($attr, array('items')) . ' />';
        }
        return $str;
    }

    /**
     * 文件域
     * @param $attr
     * @param $content
     * @return string
     * @since 1.0 2014-12-3 by sutroon
     * @example <sohtml:file name="thumbUrl" value="{$data.thumbUrl}" />
     */
    public function _file($attr, $content) {
        //$attr = $this->parseXmlAttr($attr, 'file');
        $value = $attr['value'];
        if ($value) {
            $value = $this->base_get_tpl_data($value);
            if ($value) {
                $ext = pathinfo($value, PATHINFO_EXTENSION);
                if ($ext && in_array($ext, array('jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff'))) {
                    $str = '<a href="' . $value . '" title="' . $value . '" target="_blank"><img src="' . $value . '" alt="' . $value . '" style="width: 60px; height: 60px;"></a>';
                } else {
                    $str = '<a href="' . $value . '" title="' . $value . '" target="_blank">' . $value . '</a>';
                }
                $str .= '<input type="file" ' . $this->base_attr_to_string($attr, array('value')) . ' style="display: none;"/>';
                $str .= '<a href="#" onclick="if($(this).text()==\'[更换]\'){$(this).text(\'[取消]\').prev().show().prev().hide();}else{$(this).text(\'[更换]\').prev().hide().prev().show();};return false;">[更换]</a>';
                return $str;
            }
        }
        return '<input type="file" ' . $this->base_attr_to_string($attr, array('value')) . ' />';
    }

    /**
     * 中国省市区控件
     * @param type $attr
     * @param type $content
     * @return string
     * @since 1.0 2014-12-11 by sutroon
     * @since 1.1 2016-1-25 SoChishun 新增nameattr命名属性参数
     * @example 
     *  <sohtml:region province="{$data.province}" city="{$data.city}" area="{$data.area}" names="province,city,area" nameattr="id,name" changeFunc="changeRegion" />
     *  <input type="text" name="address" />
     *  <script>
     *  // 1.0 2014-12-11 by sutroon 在文本框中加英文逗号,逗号后面的字串将被保留,如：福建省 厦门市 思明区, 湖滨南路(注意逗号位置)
     *  function changeRegion(p,c,a){var val=p;if(c){val=val+' '+c;}if(a){val=val+' '+a;}var $tb=$('input[name="address"]');var oldv=$tb.val();var pos=oldv.lastIndexOf(' ');if(pos>-1){val+=oldv.substring(pos);}
      $tb.val(val);}
     *  </script>
     */
    public function _region($attr, $content) {
        //$attr = $this->parseXmlAttr($attr, 'region');
        $names = empty($attr['names']) ? 'province,city,area' : $attr['names'];
        $anameattr = empty($attr['nameattr']) ? array('id') : explode(',', $attr['nameattr']);
        $anames = explode(',', $attr['names']);
        if (count($anames) < 3) {
            return '省市区控件初始化有误!';
        }
        $snameattr = '';
        foreach ($anameattr as $na) {
            $snameattr.=' ' . $na . '="%s"';
        }
        $province = empty($attr['province']) ? '' : $this->base_get_tpl_data($attr['province']);
        $city = empty($attr['city']) ? '' : $this->base_get_tpl_data($attr['city']);
        $area = empty($attr['area']) ? '' : $this->base_get_tpl_data($attr['area']);
        $container = isset($attr['container']) ? $attr['container'] : '';
        $changeFunc = empty($attr['changefunc']) ? '' : ', "changeFunc": ("undefined" == typeof (' . $attr['changefunc'] . ')? undefined : ' . $attr['changefunc'] . ')';
        $str = '<select' . str_replace('%s', $anames[0], $snameattr) . '></select><select' . str_replace('%s', $anames[1], $snameattr) . '></select><select' . str_replace('%s', $anames[2], $snameattr) . '></select>';
        $str.='<script>$(function () {$.cnRegion({"province": "' . $province . '", "city": "' . $city . '", "area": "' . $area . '", "names": "' . $names . '", "container": "' . $container . '"' . $changeFunc . '});});</script>';
        return $str;
    }

    // 2014-11-7 by sutroon
    private function get_checkinput($type, $attr) {
        $value = $attr['value'];
        if ($value) {
            $value = $this->base_get_tpl_data($value);
        }
        $str = '';
        $arr_items = $this->base_parse_items_array($attr);
        if (is_array(current($arr_items))) {
            foreach ($arr_items as $item) {
                $str .= '<input type="' . $type . '" name="' . $attr['name'] . '" value="' . $item['v'] . '"' . (strlen($item['v']) > 0 && $value == $item['v'] ? ' checked="checked"' : '') . $this->base_attr_to_string($attr, array('name', 'items', 'min', 'max', 'step', 'value')) . (empty($item['c']) ? '' : ' title="' . $item['c'] . '"') . ' />' . $item['t'] . ' ';
            }
        } else {
            foreach ($arr_items as $val => $txt) {
                $str .= '<input type="' . $type . '" name="' . $attr['name'] . '" value="' . $val . '"' . (strlen($value) > 0 && $value == $val ? ' checked="checked"' : '') . $this->base_attr_to_string($attr, array('name', 'items', 'min', 'max', 'step', 'value')) . ' />' . $txt . ' ';
            }
        }
        return $str;
    }

    /**
     * 排序按钮
     * @param type $attr
     * @param type $content
     * @return type
     * @since 1.0 2015-2-2 by sutroon
     * @example <sohtml:sortlink field="callRate" direct="D" param="sort" /><sohtml:sortlink field="callSuccessCount" /><sohtml:sortlink field="callFailCount" />
     */
    public function _sortlink($attr, $content) {
        //$attr = $this->parseXmlAttr($attr, 'sortlink');
        $field = $attr['field'];
        $direct = $attr['direct'];
        $param = empty($attr['param']) ? 'sort' : $attr['param'];
        $sort = I($param);
        $sortfield = false;
        if ($sort) {
            $sortfield = substr($sort, 1);
            if ($field == $sortfield) {
                $direct = $sort[0];
            } else {
                $direct = '';
            }
        }
        return '<a href="#" class="lnk-sort" onclick="return lnkSort_Click(this)" data-field="' . $field . '" data-direct="' . $direct . '" title="' . (($direct && 'D' == $direct) ? '倒序' : '升序') . '">' . (($direct && 'D' == $direct) ? '&downarrow;' : '&uparrow;') . '</a>';
    }

}
